from typing import Dict, Any, List

from util.code_lists import get_settings


def split_message_to_dicts(messages: List[Dict[str, Any]]) -> Dict[tuple, str]:
    """
    将消息列表转换为字典，键为 (name, action) 元组，值为 hex_data
    :param messages: Key设备的原始消息列表
    :return: 格式：{(name, action): hex_data, ...}
    """
    messages_dict = {}
    # 定义需要的核心字段（确保消息包含这些字段）
    required_fields = ["name", "action", "hex_data"]

    for idx, msg in enumerate(messages, 1):
        # 1. 检查当前消息是否包含所有核心字段
        missing_fields = [field for field in required_fields if field not in msg]
        if missing_fields:
            print(f"警告：跳过第{idx}条消息（缺失字段：{missing_fields}）→ 消息内容：{msg}")
            continue

        # 2. 提取核心字段，组合 (name, action) 作为元组键
        name = msg["name"]
        action = msg["action"]
        hex_data = msg["hex_data"]
        key = (name, action)  # 元组作为字典键（Python完全支持）

        # 3. 存入字典（若有重复键，后面的会覆盖前面的，确保保留最新值）
        messages_dict[key] = hex_data
        # print(f"添加键 {key} → hex_data: {hex_data}")

    # print(f"\n转换完成！共生成 {len(messages_dict)} 个键值对")
    return messages_dict

def convert(path):
    power_messages, key_messages, discrete_messages, linux_messages, flash_messages, check_messages, init_messages = get_settings(path)
    power_message_dict = split_message_to_dicts(power_messages)
    key_message_dict = split_message_to_dicts(key_messages)
    discrete_message_dict = split_message_to_dicts(discrete_messages)
    linux_message_dict = split_message_to_dicts(linux_messages)
    flash_message_dict = split_message_to_dicts(flash_messages)
    check_message_dict = split_message_to_dicts(check_messages)
    init_message_dict = split_message_to_dicts(init_messages)

    return power_message_dict, key_message_dict, discrete_message_dict, linux_message_dict, flash_message_dict, check_message_dict, init_message_dict